package com.fenda.gallery

import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.*
import android.widget.AbsListView
import androidx.fragment.app.Fragment
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.fenda.gallery.databinding.GalleryFragmentBinding
import kotlinx.coroutines.*
import kotlin.coroutines.Continuation
import kotlin.coroutines.suspendCoroutine

//加入协程
class GalleryFragment : Fragment(), CoroutineScope by MainScope() ,GalleryAdapter.GetData {

    companion object {
        fun newInstance() = GalleryFragment()
    }

    private lateinit var viewModel: GalleryViewModel
    private lateinit var dataBinding: GalleryFragmentBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dataBinding = DataBindingUtil.inflate(inflater,R.layout.gallery_fragment,container,false)
        return dataBinding.root
    }

    @ExperimentalCoroutinesApi
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        //设置menu菜单
        setHasOptionsMenu(true)
        viewModel = ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory(requireActivity().application)
        ).get(GalleryViewModel::class.java)
        val galleryAdapter = GalleryAdapter(this)

        val recyclerView = requireView().findViewById<RecyclerView>(R.id.recycleView)

        recyclerView.apply {
            adapter = galleryAdapter
//            layoutManager = GridLayoutManager(requireContext(), 2)
            //类似瀑布布局
            layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        }
        //观察数据变化
        viewModel.photoListLive.observe(requireActivity(), Observer {
            //正在加载显示位置
            if (viewModel.needToScrollToTop) {
                recyclerView.scrollToPosition(0)
                viewModel.needToScrollToTop = false
            }
            galleryAdapter.submitList(it)
            dataBinding.swipeLayoutGallery.isRefreshing = false
        })
        //观察数据量的改变
        viewModel.dataStatusLive.observe(requireActivity(),{
            galleryAdapter.footerViewStatus = it
            galleryAdapter.notifyItemChanged(galleryAdapter.itemCount - 1)
            if (it == DATA_STATUS_NETWORK_ERROR) dataBinding.swipeLayoutGallery.isRefreshing = false
        })

        //空就拉取数据
        this.launch {
            viewModel.photoListLive.value ?: viewModel.resetQuery()
        }

        dataBinding.swipeLayoutGallery.setOnRefreshListener {
            this.launch {
                viewModel.resetQuery()
            }
        }

        //滚动监听
        dataBinding.recycleView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //往上滑动就返回
                if (dy < 0)return
                val layoutManager = dataBinding.recycleView.layoutManager as StaggeredGridLayoutManager
                val inArray =  IntArray(2)
                //找到layoutManager的最后一行
                layoutManager.findLastVisibleItemPositions(inArray)
                if (inArray[0] == galleryAdapter.itemCount-1){
                    viewLifecycleOwner.lifecycleScope.launch {
                        viewModel.fetchData()
                    }
                }
            }
        })

    }

    //menu相关
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu,menu)
    }

    @ExperimentalCoroutinesApi
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.swap -> {
                dataBinding.swipeLayoutGallery.isRefreshing = true
                this.launch {  viewModel.resetQuery() }
            }
        }
        return super.onOptionsItemSelected(item)
    }


    override fun onDestroy() {
        super.onDestroy()
        //取消所有任务
        this.cancel()
    }

    @ExperimentalCoroutinesApi
    override fun callBack() {
        this.launch {
            viewModel.fetchData()
        }
    }

}


